<template>
  <div id="homePage">
    <!--搜索框-->
    <div class="search-bar">
      <a-input-search
        v-model:value="searchQueryParams.searchText"
        placeholder="从海量图片中搜索"
        enter-button="搜索"
        size="large"
        @search="onSearch"
        :loading="loading"
      />
    </div>
    <!-- 分类 + 标签 -->
    <a-tabs v-model:activeKey="selectedCategory" @change="onSearch">
      <a-tab-pane key="all" tab="全部" />
      <a-tab-pane v-for="category in categoryList" :key="category" :tab="category" />
    </a-tabs>
    <div class="tag-bar">
      <span style="margin-right: 8px">标签：</span>
      <a-space :size="[0, 8]" wrap>
        <a-checkable-tag
          v-for="(tag, index) in tagList"
          :key="tag"
          v-model:checked="selectedTagList[index]"
          @change="onSearch"
        >
          {{ tag }}
        </a-checkable-tag>
      </a-space>
    </div>

    <!-- 图片列表 新的调整使用图片列表组件,并补充分页组件-->
    <PictureList :dataList="dataList" :canEdit="false" :canDelete="false" :loading="loading" />
    <!-- 分页组件-->
    <a-pagination
      v-if="shouldShowPagination"
      v-model:current="searchQueryParams.pageNum"
      v-model:page-size="searchQueryParams.pageSize"
      :total="total"
      responsive
      show-size-changer
      show-quick-jumper
      :page-size-options="pageSizeOptions"
      :show-total="(total) => `共 ${total} 条记录`"
      @change="onPageChange"
      style="text-align: right"
    >
      <template #buildOptionText="props">
        <span class="custom-option-text">{{ props.value }}条/页</span>
      </template>
    </a-pagination>
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, reactive, ref } from 'vue'
import {
  listPictureTagCategoryUsingGet,
  listPictureVoByPageUsingPost,
} from '@/api/pictureController.ts'
import { message } from 'ant-design-vue'
import { useRouter } from 'vue-router'
import PictureList from '@/components/PictureList.vue'

const pageSizeOptions = ref<string[]>(['10', '20', '30', '40', '50'])
const dataList = ref([])
const loading = ref(false)
const total = ref(0)

// 计算属性：判断是否需要显示分页器
const shouldShowPagination = computed(() => {
  // 如果 dataList 为空或长度小于分页大小（例如 pageSize），则将分页器隐藏或设置为不可见。
  return (
    dataList.value.length >= searchQueryParams.pageSize && total.value > searchQueryParams.pageSize
  )
})
const onPageChange = (pageNum: number, pageSize: number) => {
  searchQueryParams.pageNum = pageNum
  searchQueryParams.pageSize = pageSize
  searchList()
}

// 定义查询参数对象，用于分页及搜索条件传递给后端接口
const searchQueryParams = reactive<API.PictureQueryRequest>({
  pageNum: 1,
  pageSize: 10,
})

// 查询用户列表：根据当前的查询参数向后端请求用户数据
const searchList = async () => {
  if (loading.value) return
  loading.value = true
  try {
    const params = {
      ...searchQueryParams,
      tags: [],
    }
    if (selectedCategory.value !== 'all') {
      params.category = selectedCategory.value
    }
    if (selectedTagList.value.length > 0) {
      // 选中的标签内容 = [true, true]
      // console.log('selectedTagList', selectedTagList.value)
      // 遍历选中的标签，将标签名添加到params.tags中
      selectedTagList.value.forEach((tag, index) => {
        if (tag) {
          params.tags.push(tagList.value[index])
        }
      })
    }
    const res = await listPictureVoByPageUsingPost(params)
    if (res.code === 0 && res.data) {
      dataList.value = res.data.records
      total.value = Number(res.data.total)
    }
  } catch (e) {
    message.error('加载图片失败，' + e.message)
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  searchList()
})

// 通用重置函数
const resetQueryParams = async () => {
  // 重置分页参数
  searchQueryParams.pageNum = 1
}

const onSearch = async (value: string) => {
  await resetQueryParams()
  await searchList()
}

const categoryList = ref<string[]>([])
const selectedCategory = ref<string>('all')
const tagList = ref<string[]>([])
const selectedTagList = ref<string[]>([])

// 获取标签和分类选项
const getTagCategoryOptions = async () => {
  const res = await listPictureTagCategoryUsingGet()
  if (res.code === 0 && res.data) {
    // 转换成下拉选项组件接受的格式
    categoryList.value = res.data.categoryList ?? []
    tagList.value = res.data.tagList ?? []
  } else {
    message.error('加载分类标签失败，' + res.data.message)
  }
}

onMounted(() => {
  getTagCategoryOptions()
})
const router = useRouter()
// 点击图片跳转图片详情页
const doClickPicture = (picture: API.PictureVO) => {
  router.push({
    path: `/picture/${picture.id}`,
  })
}
</script>

<style scoped>
#homePage {
  margin-bottom: 16px;
}

#homePage .search-bar {
  max-width: 480px;
  margin: 0 auto 16px;
}

#homePage .tag-bar {
  margin-bottom: 20px;
}
</style>
